//
//  BHCompetitionDetailViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/6/15.
//  赛事详情
    
import UIKit

class BHCompetitionDetailViewController: BHBaseViewController {

    
    lazy var navigationBar: BHCompetitionDetailNavBar = {
        let view = BHCompetitionDetailNavBar.loadFromXib()
        view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.begainY)
        view.backgroundColor = UIColor.color_34CE98.withAlphaComponent(0.0)
        view.delegate = self
        return view
    }()
    
    lazy var bottomView: BHCompetionDetailBottomView = {
        let view = BHCompetionDetailBottomView.loadFromXib()
        view.frame = CGRect(x: 0, y: UIScreen.height-BHCompetionDetailBottomView.bottomHeight, width: UIScreen.width, height: BHCompetionDetailBottomView.bottomHeight)
        view.delegate = self
        return view
    }()
    
    lazy var secView: BHCompetitionSecView = {
        let view = BHCompetitionSecView.loadFromXib()
        view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: BHCompetitionSecView.headerHeight)
        view.delegate = self
        return view
    }()
    
    lazy var tableView: UITableView = {
        let view = UITableView.buildTableView(style: .grouped)
        view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.height-BHCompetionDetailBottomView.bottomHeight)
        view.delegate = self
        view.isHidden = true
        view.dataSource = self
        return view
    }()
    
    
    lazy var headerView: BHCompetitionDetailHeaderView = {
        let view = BHCompetitionDetailHeaderView.loadFromXib()
        view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: BHCompetitionDetailHeaderView.headerHeight)
        return view
    }()
    
    lazy var introduceWebCell: BHHtmlContentWebCell = { [weak self] in
        let cell = self?.tableView.dequeueReusableCell(withIdentifier: "BHHtmlContentWebCell", for: IndexPath.init(row: 0, section: 0)) as! BHHtmlContentWebCell
        return cell
    }()
    
    lazy var signAlertView: BHCompetitionSignAlertView = {
        let view = BHCompetitionSignAlertView.loadFromXib()
        return view
    }()
    
    lazy var serviceManager: BHCompetitionServiceManager = {
        let manager = BHCompetitionServiceManager.init()
        return manager
    }()
     
    fileprivate var detailModel = BHCompetitionDetailModel.init()
    fileprivate var livingUrl: String = ""
    fileprivate var dynArray: [BHCompetitionDynModel] = []
    fileprivate var introduceHeight: CGFloat = 0
    fileprivate var reportArray: [BHCompetitionReportModel] = []

    var gameId: String = ""
    
    
    /**0赛事报道  1赛时动态  2相关报道*/
    fileprivate var changeType: Int = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.serviceManager.gameId = self.gameId
        
        self.bh_navigationBar.removeFromSuperview()
        self.view.addSubview(self.tableView)
        self.view.addSubview(self.navigationBar)
        self.view.addSubview(self.bottomView)
        self.view.addSubview(self.signAlertView)
        self.regisetCell()
        
        self.tableView.tableHeaderView = self.headerView
        
        
        self.headerView.applyDetailBtn.addBtnAction(action: {[weak self] (_) in
            BHRouter.shared.bh_goUserList(type: 3, userId: nil, businessId: self?.gameId)
        }, for: .touchUpInside)
        
        self.serviceObserver()
        
        self.serviceManager.loadCompetitionDetailService()
        
        self.introduceWebCell.webCellCallRealHeightBlock = { [weak self] height in
            self?.introduceHeight = height
            self?.tableView.reloadData()
        }
    }
    
}

extension BHCompetitionDetailViewController {
    func regisetCell()  {
        self.tableView.register(UINib.init(nibName: "BHCompetitionDetailFiledCell", bundle: nil), forCellReuseIdentifier: "BHCompetitionDetailFiledCell")
        self.tableView.register(UINib.init(nibName: "BHCompetitionTipTableViewCell", bundle: nil), forCellReuseIdentifier: "BHCompetitionTipTableViewCell")
        self.tableView.register(UINib.init(nibName: "BHCompetitionRelationReportCell", bundle: nil), forCellReuseIdentifier: "BHCompetitionRelationReportCell")
        self.tableView.register(UINib.init(nibName: "BHCompetitionLivelinkCell", bundle: nil), forCellReuseIdentifier: "BHCompetitionLivelinkCell")
        self.tableView.regiseterNib(nibName: "BHCompetitionImageOrVideoCell")
        self.tableView.register(BHHtmlContentWebCell.self, forCellReuseIdentifier: "BHHtmlContentWebCell")
    }
}

extension BHCompetitionDetailViewController: BHCompetitionDetailNavBarDelegate {
    func navigationBarDidBackAction() {
        self.navigationController?.popViewController(animated: true)
    }
    // 0 是分享 1是收藏
    func navigationBarDidShareOrCollectAction(type: Int, collectOrNot: Bool) {
        if type == 1 {
            self.attentionOrNot()
        }
        if type == 0 {
            BHToast.toast(text: String.serviceWaiteOpen)
        }
    }
}

extension BHCompetitionDetailViewController: BHCompetionDetailBottomViewDelegate {
    /**0报名 1签到  2群聊  3咨询*/
    func bottomDidSelectTypeAction(type: Int) {
        if type == 0 {
            if self.detailModel.eventType == 0 {
                return
            }
            if self.detailModel.status != 1 {
                return
            }
            let applyVC = BHCompetitionApplyViewController.init()
            applyVC.gameId = self.gameId
            applyVC.applyType = self.detailModel.eventType-1
            self.navigationController?.pushViewController(applyVC, animated: true)
            applyVC.refreshDetailBlock = { [weak self] in
                self?.serviceManager.loadCompetitionDetailService()
            }
        }else if type == 1{
            if self.detailModel.whetherSignin == 1 {
                SVProgressHUD.show()
                self.serviceManager.gameSignService()
            }else {
                BHToast.toast(text: "当前赛事无需签到")
            }
            
        }else if type == 2{
//            BHToast.toast(text: String.serviceWaiteOpen)
//            0报名已截止 1可以报名 2已报名 3赛事已结束 4报名已满
            if self.detailModel.status == 2 {
                if self.detailModel.groupNumber.isEmpty == true {
                    BHToast.toast(text: "当前赛事群未组建")
                    return
                }
                BHRouter.shared.bh_goGroupChat(groupId: self.detailModel.groupNumber)
            }else {
                BHToast.toast(text: "您当前并未报名该赛事")
            }
            
        }else {
            if self.detailModel.contactNumber.isEmpty == true {
                BHToast.toast(text: "当前场馆暂无电话")
                return;
            }
            BHCommonTool.telAct(self.detailModel.contactNumber) { (open) in
                if open == false {
                    BHToast.toast(text: "当前设备暂不支持拨打电话")
                }
            }
        }
    }
}
extension BHCompetitionDetailViewController: BHCompetitionSecViewDelegate {
    func changeTypeDidSelectAct(type: Int) {
        self.changeType = type
        if type == 1 { // 动态
            self.serviceManager.queryDynService()
        }
        if type == 2 { // 报道
            self.serviceManager.queryReportService()
        }
        self.tableView.reloadData()
    }
}



extension BHCompetitionDetailViewController: UITableViewDataSource {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
      
        if scrollView == self.tableView {
            if scrollView.contentOffset.y <= 0 {
                self.navigationBar.backgroundColor = UIColor.color_34CE98.withAlphaComponent(0.0)
            }else {
                var alpha = scrollView.contentOffset.y/UIScreen.begainY
                if alpha > 1 {
                    alpha = 1
                }
                self.navigationBar.backgroundColor = UIColor.color_34CE98.withAlphaComponent(alpha)
            }
            
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.changeType == 0 {
            return self.rowForTypeOne(section: section)
        }
        if self.changeType == 1 {
            return self.rowForTypeTwo(section: section)
        }
        if self.changeType == 2 {
            return self.rowForTypeThree(section: section)
        }
        return 0
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if self.changeType == 0 {
            return self.heightForTypeOne(indexPath: indexPath)
        }
        if self.changeType == 1 {
            return self.heightForTypeTwo(indexPath: indexPath)
        }
        if self.changeType == 2 {
            return self.heightForTypeThree(indexPath: indexPath)
        }
        return 60
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return  BHCompetitionSecView.headerHeight
    }
    
}

extension BHCompetitionDetailViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return self.secView
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if self.changeType == 0 {
            return self.cellForTypeOne(indexPath: indexPath)
        }
        if self.changeType == 1 {
            return self.cellForTypeTwo(indexPath: indexPath)
        }
        if self.changeType == 2 {
            return self.cellForTypeThree(indexPath: indexPath)
        }
        return UITableViewCell.init()
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if self.changeType == 2 {
            let model = self.reportArray[indexPath.row]
            let reportDetailVC = BHReportDetailViewController.init()
            reportDetailVC.model = model
            self.navigationController?.pushViewController(reportDetailVC, animated: true)
        }
    }
}


// 赛事报道
extension BHCompetitionDetailViewController {
    func rowForTypeOne(section: Int) -> Int {
        return 3
    }
    
    func heightForTypeOne(indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 {
            return self.introduceHeight
        }
        else if indexPath.row == 1 {
            return BHCompetitionDetailFiledCell.cellHeight
        }
        else {
            return BHCompetitionTipTableViewCell.cellHeight
        }
    }
    
    func cellForTypeOne(indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            return self.introduceWebCell
        }else if indexPath.row == 1 {
            let cell = self.tableView.dequeueReusableCell(withIdentifier: "BHCompetitionDetailFiledCell", for: indexPath) as! BHCompetitionDetailFiledCell
            // 下载文件
            cell.downFiledBtn.addBtnAction(action: { (_) in
                BHToast.toast(text: String.serviceWaiteOpen)
            }, for: .touchUpInside)
            return cell
        }else {
            let cell = self.tableView.dequeueReusableCell(withIdentifier: "BHCompetitionTipTableViewCell", for: indexPath) as! BHCompetitionTipTableViewCell
            cell.backRuleBtn.setTitle(" \(self.detailModel.backRule)", for: .normal)
            return cell
        }
    }
}

// 相关动态
extension BHCompetitionDetailViewController {
    func rowForTypeTwo(section: Int) -> Int {
        return 1+self.dynArray.count
    }
    
    func heightForTypeTwo(indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 {
            return 132
        }else {
            let model = self.dynArray[indexPath.row-1]
            return model.height
        }
    }
    
    func cellForTypeTwo(indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell = self.tableView.dequeueReusableCell(withIdentifier: "BHCompetitionLivelinkCell", for: indexPath) as! BHCompetitionLivelinkCell
            if self.livingUrl.isEmpty == true {
                cell.linkBtn.setTitle(" 当前赛事暂无直播", for: .normal)
            }else {
                cell.linkBtn.setTitle(" 点击查看赛事直播", for: .normal)
            }
            cell.linkBackView.addViewAction {[weak self] (_) in
                if self?.livingUrl.isEmpty == true {
                    BHToast.toast(text: "当前赛事暂无直播")
                    return
                }
                BHCommonTool.showAlertWith(showVC: nil, title: "提示", message: "是否立即前往直播？", okBtn: "立即前往", cancel: "等会再去") { (confirm) in
                    if confirm == true {
                        UIApplication.shared.open(URL.init(string: self?.livingUrl ?? "")! , options: [ : ], completionHandler: nil)
                    }
                }
            }
            return cell

        }else {
            let cell = self.tableView.dequeueReusableCell(withIdentifier: "BHCompetitionImageOrVideoCell", for: indexPath) as! BHCompetitionImageOrVideoCell
            let model = self.dynArray[indexPath.row-1]
            cell.model = model
            return cell

        }
    }
}

// 相关报道
extension BHCompetitionDetailViewController {
    func rowForTypeThree(section: Int) -> Int {
        return self.reportArray.count
    }
    
    func heightForTypeThree(indexPath: IndexPath) -> CGFloat {
        let model = self.reportArray[indexPath.row]
        return model.height
    }
    
    func cellForTypeThree(indexPath: IndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "BHCompetitionRelationReportCell", for: indexPath) as! BHCompetitionRelationReportCell
        let model = self.reportArray[indexPath.row]
        cell.model = model
        return cell
    }
}


// 接口
extension BHCompetitionDetailViewController {
    func serviceObserver()  {
        // 主详情的接口回调
        self.serviceManager.responseForMainDetailBlock = { [weak self] model in
            self?.detailModel = model
            
            self?.headerView.model = model
            
            self?.navigationBar.collected = model.ifAttention == 1
            
            self?.tableView.isHidden = false
            self?.introduceWebCell.htmlText = model.introduce
            self?.tableView.reloadData()
            self?.bottomView.model = model
        }
        
        // 动态回调
        self.serviceManager.responseForDynBlock = {[weak self] (livingUrl,dynArray) in
            self?.livingUrl = livingUrl
            self?.dynArray = dynArray
            self?.tableView.reloadData()
        }
        
        // 报道回调
        self.serviceManager.responseForReportBlock = { [weak self] (success,errorMsg,arrary) in
            if success == true {
                self?.reportArray = arrary
                self?.tableView.reloadData()
            }
            
        }
        
        // 签到的回调
        self.serviceManager.responseForSignInBlock =  {[weak self] (success, errorMsg) in
            SVProgressHUD.dismiss()
            if success == true {
                self?.signAlertView.type = 0
                self?.signAlertView.state = "签到成功"
                self?.signAlertView.content = "若存在押金等费用，待比赛结束后相关费用\n将在3个工作日内退回原账户"
                self?.signAlertView.show()
                
                self?.bottomView.signBtn.isSelected = true
            }else {
                self?.signAlertView.type = 1
                self?.signAlertView.state = "签到失败"
                self?.signAlertView.content = errorMsg
                self?.signAlertView.show()
            }
        }
    }
    
    func attentionOrNot()  {
        SVProgressHUD.show()
        BHCommonService.collectOrNotService(type: 3, businessId: self.gameId) { (success, errorMsg) in
            SVProgressHUD.dismiss()
            if success == true {
                if self.detailModel.ifAttention == 1 { // 取消
                    self.detailModel.ifAttention = 0
                    
                    BHToast.toast(text: "关注已取消")
                }else {
                    self.detailModel.ifAttention = 1
                    
                    BHToast.toast(text: "已关注")
                }
                
                self.navigationBar.collected = self.detailModel.ifAttention == 1

            }else {
                BHToast.toast(text: errorMsg)
            }
        }
    
    }
}
